﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;

namespace TfsPolicyPack.CustomRegexPathPolicy.Forms
{
    public partial class EditForm : Form
    {
        #region Constructor

        public EditForm()
        {
            InitializeComponent();
        }

        #endregion

        #region Public Methods

        public void Init(IEnumerable<TfsPolicy> availablePolicies, PolicySettings settings)
        {
            IncludeList.Init(settings.IncludeList);
            ExcludeList.Init(settings.ExcludeList);

            foreach (TfsPolicy policy in availablePolicies)
                PolicyCheckBoxList.Items.Add(policy, settings.AffectedPolicies.Exists(p => p.UniqueName == policy.UniqueName));

            RefreshUserInterface();
        }

        public PolicySettings GetSettings()
        {
            return new PolicySettings
            {
                ExcludeList = ExcludeList.GetPatterns(),
                IncludeList = IncludeList.GetPatterns(),
                AffectedPolicies = PolicyCheckBoxList.CheckedItems.OfType<TfsPolicy>().Select(p => new PolicyInfo(p.Type, p.Occurrence)).ToList()
            };
        }

        #endregion

        #region Non Public Methods

        private void RegExEditControl_Changed(object sender, EventArgs e)
        {
            RefreshUserInterface();
        }

        private void PolicyCheckBoxList_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshUserInterface();
        }

        private void RefreshUserInterface()
        {
            OkButton.Enabled = PolicyCheckBoxList.CheckedItems.Count > 0 && (IncludeList.HasPatterns() || ExcludeList.HasPatterns());
        }

        private void OkButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        #endregion
    }
}